//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package cn.afterturn.easypoi.excel.export.base;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.exception.excel.ExcelExportException;
import cn.afterturn.easypoi.exception.excel.enums.ExcelExportEnum;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import cn.afterturn.easypoi.handler.inter.IExcelDictHandler;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import cn.afterturn.easypoi.util.PoiReflectorUtil;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 覆盖jar中的类，修改类中的方法
 */
public class ExportCommonService {
    protected static final Logger LOGGER = LoggerFactory.getLogger(ExportCommonService.class);
    protected IExcelDataHandler dataHandler;
    protected IExcelDictHandler dictHandler;
    protected List<String> needHandlerList;

    public ExportCommonService() {
    }

    private ExcelExportEntity createExcelExportEntity(Field field, String targetId, Class<?> pojoClass, List<Method> getMethods, ExcelEntity excelGroup) throws Exception {
        Excel excel = (Excel)field.getAnnotation(Excel.class);
        ExcelExportEntity excelEntity = new ExcelExportEntity();
        excelEntity.setType(excel.type());
        this.getExcelField(targetId, field, excelEntity, excel, pojoClass, excelGroup);
        if (getMethods != null) {
            List<Method> newMethods = new ArrayList();
            newMethods.addAll(getMethods);
            newMethods.add(excelEntity.getMethod());
            excelEntity.setMethods(newMethods);
        }

        return excelEntity;
    }

    private Object dateFormatValue(Object value, ExcelExportEntity entity) throws Exception {
        Date temp = null;
        SimpleDateFormat format;
        if (value instanceof String && StringUtils.isNoneEmpty(new CharSequence[]{value.toString()})) {
            format = new SimpleDateFormat(entity.getDatabaseFormat());
            temp = format.parse(value.toString());
        } else if (value instanceof Date) {
            temp = (Date)value;
        } else if (value instanceof java.sql.Date) {
            temp = new Date(((java.sql.Date)value).getTime());
        } else if (value instanceof Time) {
            temp = new Date(((Time)value).getTime());
        } else if (value instanceof Timestamp) {
            temp = new Date(((Timestamp)value).getTime());
        }

        if (temp != null) {
            format = new SimpleDateFormat(entity.getFormat());
            value = format.format(temp);
        }

        return value;
    }

    private Object numFormatValue(Object value, ExcelExportEntity entity) {
        if (value == null) {
            return null;
        } else if (!NumberUtils.isNumber(value.toString())) {
            LOGGER.error("data want num format ,but is not num, value is:" + value);
            return null;
        } else {
            Double d = Double.parseDouble(value.toString());
            DecimalFormat df = new DecimalFormat(entity.getNumFormat());
            return df.format(d);
        }
    }

    public void getAllExcelField(String[] exclusions, String targetId, Field[] fields, List<ExcelExportEntity> excelParams, Class<?> pojoClass, List<Method> getMethods, ExcelEntity excelGroup) throws Exception {
        List<String> exclusionsList = exclusions != null ? Arrays.asList(exclusions) : null;

        for(int i = 0; i < fields.length; ++i) {
            Field field = fields[i];
            if (!PoiPublicUtil.isNotUserExcelUserThis(exclusionsList, field, targetId)) {
                if (field.getAnnotation(Excel.class) != null) {
                    Excel excel = (Excel)field.getAnnotation(Excel.class);
                    String name = PoiPublicUtil.getValueByTargetId(excel.name(), targetId, (String)null);
                    if (StringUtils.isNotBlank(name)) {
                        excelParams.add(this.createExcelExportEntity(field, targetId, pojoClass, getMethods, excelGroup));
                    }
                } else if (PoiPublicUtil.isCollection(field.getType())) {
                    ExcelCollection excel = (ExcelCollection)field.getAnnotation(ExcelCollection.class);
                    ParameterizedType pt = (ParameterizedType)field.getGenericType();
                    Class<?> clz = (Class)pt.getActualTypeArguments()[0];
                    List<ExcelExportEntity> list = new ArrayList();
                    this.getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, PoiPublicUtil.getClassFields(clz), list, clz, (List)null, (ExcelEntity)null);
                    ExcelExportEntity excelEntity = new ExcelExportEntity();
                    excelEntity.setName(PoiPublicUtil.getValueByTargetId(excel.name(), targetId, (String)null));
                    excelEntity.setOrderNum(Integer.valueOf(PoiPublicUtil.getValueByTargetId(excel.orderNum(), targetId, "0")));
                    excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName()));
                    excelEntity.setList(list);
                    excelParams.add(excelEntity);
                } else {
                    List<Method> newMethods = new ArrayList();
                    if (getMethods != null) {
                        newMethods.addAll(getMethods);
                    }

                    newMethods.add(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName()));
                    ExcelEntity excel = (ExcelEntity)field.getAnnotation(ExcelEntity.class);
                    if (excel.show() && StringUtils.isEmpty(excel.name())) {
                        throw new ExcelExportException("if use ExcelEntity ,name mus has value ,data: " + ReflectionToStringBuilder.toString(excel), ExcelExportEnum.PARAMETER_ERROR);
                    }

                    this.getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, PoiPublicUtil.getClassFields(field.getType()), excelParams, field.getType(), newMethods, excel.show() ? excel : null);
                }
            }
        }

    }

    public Object getCellValue(ExcelExportEntity entity, Object obj) throws Exception {
        Object value;
        if (obj instanceof Map) {
            value = ((Map)obj).get(entity.getKey());
        } else {
            value = entity.getMethods() != null ? this.getFieldBySomeMethod(entity.getMethods(), obj) : entity.getMethod().invoke(obj);
        }

        if (StringUtils.isNotEmpty(entity.getFormat())) {
            value = this.dateFormatValue(value, entity);
        }

        if (entity.getReplace() != null && entity.getReplace().length > 0) {
            value = this.replaceValue(entity.getReplace(), String.valueOf(value));
        }

        if (StringUtils.isNotEmpty(entity.getNumFormat())) {
            value = this.numFormatValue(value, entity);
        }

        if (StringUtils.isNotEmpty(entity.getDict()) && this.dictHandler != null) {
            value = this.dictHandler.toName(entity.getDict(), obj, entity.getName(), value);
        }

        if (this.needHandlerList != null && this.needHandlerList.contains(entity.getName())) {
            value = this.dataHandler.exportHandler(obj, entity.getName(), value);
        }

        if (StringUtils.isNotEmpty(entity.getSuffix()) && value != null) {
            value = value + entity.getSuffix();
        }

        return value == null ? "" : value.toString();
    }

    public Collection<?> getListCellValue(ExcelExportEntity entity, Object obj) throws Exception {
        Object value;
        if (obj instanceof Map) {
            value = ((Map)obj).get(entity.getKey());
        } else {
            value = (Collection)entity.getMethod().invoke(obj);
        }

        return (Collection)value;
    }

    private void getExcelField(String targetId, Field field, ExcelExportEntity excelEntity, Excel excel, Class<?> pojoClass, ExcelEntity excelGroup) throws Exception {
        excelEntity.setName(PoiPublicUtil.getValueByTargetId(excel.name(), targetId, (String)null));
        excelEntity.setWidth(excel.width());
        excelEntity.setHeight(excel.height());
        excelEntity.setNeedMerge(excel.needMerge());
        excelEntity.setMergeVertical(excel.mergeVertical());
        excelEntity.setMergeRely(excel.mergeRely());
        excelEntity.setReplace(excel.replace());
        excelEntity.setOrderNum(Integer.valueOf(PoiPublicUtil.getValueByTargetId(excel.orderNum(), targetId, "0")));
        excelEntity.setWrap(excel.isWrap());
        excelEntity.setExportImageType(excel.imageType());
        excelEntity.setSuffix(excel.suffix());
        excelEntity.setDatabaseFormat(excel.databaseFormat());
        excelEntity.setFormat(StringUtils.isNotEmpty(excel.exportFormat()) ? excel.exportFormat() : excel.format());
        excelEntity.setStatistics(excel.isStatistics());
        excelEntity.setHyperlink(excel.isHyperlink());
        excelEntity.setMethod(PoiReflectorUtil.fromCache(pojoClass).getGetMethod(field.getName()));
        excelEntity.setNumFormat(excel.numFormat());
        excelEntity.setColumnHidden(excel.isColumnHidden());
        excelEntity.setDict(excel.dict());
        if (excelGroup != null) {
            excelEntity.setGroupName(PoiPublicUtil.getValueByTargetId(excelGroup.name(), targetId, (String)null));
        } else {
            excelEntity.setGroupName(excel.groupName());
        }

    }

    public Object getFieldBySomeMethod(List<Method> list, Object t) throws Exception {
        Method m;
        for(Iterator var3 = list.iterator(); var3.hasNext(); t = m.invoke(t)) {
            m = (Method)var3.next();
            if (t == null) {
                t = "";
                break;
            }
        }

        return t;
    }

    public short getRowHeight(List<ExcelExportEntity> excelParams) {
        double maxHeight = 0.0D;

        for(int i = 0; i < excelParams.size(); ++i) {
            maxHeight = maxHeight > ((ExcelExportEntity)excelParams.get(i)).getHeight() ? maxHeight : ((ExcelExportEntity)excelParams.get(i)).getHeight();
            if (((ExcelExportEntity)excelParams.get(i)).getList() != null) {
                for(int j = 0; j < ((ExcelExportEntity)excelParams.get(i)).getList().size(); ++j) {
                    maxHeight = maxHeight > ((ExcelExportEntity)((ExcelExportEntity)excelParams.get(i)).getList().get(j)).getHeight() ? maxHeight : ((ExcelExportEntity)((ExcelExportEntity)excelParams.get(i)).getList().get(j)).getHeight();
                }
            }
        }

        return (short)((int)(maxHeight * 50.0D));
    }

    private Object replaceValue(String[] replace, String value) {
        String[] var4 = replace;
        int var5 = replace.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            String str = var4[var6];
            String[] temp = str.split("_",2);
            if (value.equals(temp[1])) {
                value = temp[0];
                break;
            }
        }

        return value;
    }

    public void sortAllParams(List<ExcelExportEntity> excelParams) {
        Map<String, List<ExcelExportEntity>> groupMap = new HashMap();

        for(int i = excelParams.size() - 1; i > -1; --i) {
            if (((ExcelExportEntity)excelParams.get(i)).getList() != null) {
                Collections.sort(((ExcelExportEntity)excelParams.get(i)).getList());
            } else if (StringUtils.isNoneEmpty(new CharSequence[]{((ExcelExportEntity)excelParams.get(i)).getGroupName()})) {
                if (!groupMap.containsKey(((ExcelExportEntity)excelParams.get(i)).getGroupName())) {
                    groupMap.put(((ExcelExportEntity)excelParams.get(i)).getGroupName(), new ArrayList());
                }

                ((List)groupMap.get(((ExcelExportEntity)excelParams.get(i)).getGroupName())).add(excelParams.get(i));
                excelParams.remove(i);
            }
        }

        Collections.sort(excelParams);
        if (groupMap.size() > 0) {
            Iterator it = groupMap.entrySet().iterator();

            while(it.hasNext()) {
                Entry<String, List<ExcelExportEntity>> entry = (Entry)it.next();
                Collections.sort((List)entry.getValue());
                boolean isInsert = false;
                String groupName = "START";

                for(int i = 0; i < excelParams.size(); ++i) {
                    if (((ExcelExportEntity)excelParams.get(i)).getOrderNum() > ((ExcelExportEntity)((List)entry.getValue()).get(0)).getOrderNum() && !groupName.equals(((ExcelExportEntity)excelParams.get(i)).getGroupName())) {
                        if (StringUtils.isNotEmpty(((ExcelExportEntity)excelParams.get(i)).getGroupName())) {
                            groupName = ((ExcelExportEntity)excelParams.get(i)).getGroupName();
                        }

                        excelParams.addAll(i, (Collection)entry.getValue());
                        isInsert = true;
                        break;
                    }

                    if (!groupName.equals(((ExcelExportEntity)excelParams.get(i)).getGroupName()) && StringUtils.isNotEmpty(((ExcelExportEntity)excelParams.get(i)).getGroupName())) {
                        groupName = ((ExcelExportEntity)excelParams.get(i)).getGroupName();
                    }
                }

                if (!isInsert) {
                    excelParams.addAll((Collection)entry.getValue());
                }
            }
        }

    }

    public ExcelExportEntity indexExcelEntity(ExportParams entity) {
        ExcelExportEntity exportEntity = new ExcelExportEntity();
        exportEntity.setOrderNum(-2147483648);
        exportEntity.setName(entity.getIndexName());
        exportEntity.setWidth(10.0D);
        exportEntity.setFormat("isAddIndex");
        return exportEntity;
    }

    public int getFieldLength(List<ExcelExportEntity> excelParams) {
        int length = -1;

        ExcelExportEntity entity;
        for(Iterator var3 = excelParams.iterator(); var3.hasNext(); length += entity.getList() != null ? entity.getList().size() : 1) {
            entity = (ExcelExportEntity)var3.next();
        }

        return length;
    }

    public int getRowNums(List<ExcelExportEntity> excelParams) {
        for(int i = 0; i < excelParams.size(); ++i) {
            if (((ExcelExportEntity)excelParams.get(i)).getList() != null && StringUtils.isNotBlank(((ExcelExportEntity)excelParams.get(i)).getName())) {
                return 2;
            }

            if (StringUtils.isNoneEmpty(new CharSequence[]{((ExcelExportEntity)excelParams.get(i)).getGroupName()})) {
                return 2;
            }
        }

        return 1;
    }
}
